<template>
  <div class="card">
    <el-card header="欢迎光临">
      <el-form
        :model="formData"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :label-position="labelPosition"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>


<script>
import { Login } from "../api/users";
import { setToken} from "../utils/auth";
export default {
  data() {
    return {
      //表单标签左对齐
      labelPosition: "left",
      formData: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          Login(this.formData)
            .then(( data ) => {
              let res = data;
              console.log(data);
              if (res.code === 1000) {
                console.log(data);
                setToken(data.data.token,data.data.refreshToken)
                this.$router.push("/dashboard");
                this.$message({
                  type: "success",
                  message: res.msg
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          this.$message({
            type: "error",
            message: "请输入用户名或密码"
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style >
body {
  margin: 0px !important;
}
.el-card {
  width: 480px;
  margin: auto;
  margin-top: 10%;
  border-radius: 10px;
  padding: 50px 50px;
}
.card {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: linear-gradient(-90deg, #29bdd9 0%, #276ace 100%);
}
.el-card__header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
</style>